# -*- coding: utf-8 -*-

import torch
import tqdm
import torch.nn as nn
from torch.optim import Adam
from torch.utils.data import DataLoader

from ..model import BERTLM, BERT
from .optim_schedule import ScheduledOptim


class BERTTrainer:
    """
    BERTTrainer类 通过两种LM训练方法制作了预训练的BERT模型。
        1. Masked Language Model : 3.3.1 Task #1: Masked LM
        2. Next Sentence prediction : 3.3.2 Task #2: Next Sentence Prediction
    请通过简单的示例检查README.md的详细信息。

    """

    def __init__(self, bert: BERT,
                 vocab_size: int,
                 train_dataloader: DataLoader,
                 test_dataloader: DataLoader = None,
                 lr: float = 1e-4,
                 betas=(0.9, 0.999),
                 weight_decay: float = 0.01,
                 warmup_steps=10000,
                 with_cuda: bool = True,
                 cuda_devices=None,
                 log_freq: int = 10):
        """
        :param bert:             想训练的 BERT 模型
        :param vocab_size:       单词词汇的总数
        :param train_dataloader: 训练数据集加载器
        :param test_dataloader:  测试数据集加载器 [can be None]
        :param lr:               优化器的学习速率
        :param betas:            Adam优化器betas
        :param weight_decay:     Adam优化器权重衰减参数
        :param with_cuda:        是否使用cuda训练
        :param log_freq:         批处理迭代时的记录频率
        """

        # 设置cuda是否可用
        cuda_condition = torch.cuda.is_available() and with_cuda
        self.device = torch.device("cuda:0" if cuda_condition else "cpu")

        # 在每个epoch，bert模型将会保存
        self.bert = bert

        # 用BERT语言模型初始化BERT模型
        self.model = BERTLM(bert, vocab_size).to(self.device)

        # 如果CUDA可以检测到1个以上的GPU， 则使用分布式GPU训练
        if with_cuda and torch.cuda.device_count() > 1:
            print("Using %d GPUS for BERT" % torch.cuda.device_count())
            self.model = nn.DataParallel(self.model, device_ids=cuda_devices)

        # 设置训练和测试数据加载器
        self.train_data = train_dataloader
        self.test_data = test_dataloader

        # 使用超参数设置Adam优化器
        self.optim = Adam(self.model.parameters(), lr=lr, betas=betas, weight_decay=weight_decay)
        self.optim_schedule = ScheduledOptim(self.optim, self.bert.hidden, n_warmup_steps=warmup_steps)

        # 利用负对数似然损失函数预测 masked_token
        self.criterion = nn.NLLLoss(ignore_index=0)

        self.log_freq = log_freq

        print("Total Parameters:", sum([p.nelement() for p in self.model.parameters()]))

    def train(self, epoch):
        """模型训练"""
        self.iteration(epoch, self.train_data)

    def test(self, epoch):
        """模型测试"""
        self.iteration(epoch, self.test_data, train=False)

    def iteration(self, epoch, data_loader, train=True):
        """
        循环数据加载器，进行模型训练和测试。
        如果处于模型训练状态，反向传播被激活，并且每个epoch将会自动保存模型

        :param epoch: 当前的epoch索引
        :param data_loader: 用于迭代的torch.utils.data.DataLoader
        :param train: 训练或测试的布尔值
        :return: None
        """
        str_code = "train" if train else "test"

        # 设置tqdm进度栏
        data_iter = tqdm.tqdm(enumerate(data_loader),
                              desc="EP_%s:%d" % (str_code, epoch),
                              total=len(data_loader),
                              bar_format="{l_bar}{r_bar}")

        avg_loss = 0.0
        total_correct = 0
        total_element = 0
        for i, data in data_iter:
            # 0. 批数据将被发送到设备（GPU或cpu）
            data = {key: value.to(self.device) for key, value in data.items()}

            # 1. 前向传播下一个句子的预测和掩蔽模型
            next_sent_output, mask_lm_output = self.model.forward(data["bert_input"], data["segment_label"])

            # 2-1. is_next 分类结果的 NLL（负对数似然）损失
            next_loss = self.criterion(next_sent_output, data["is_next"])

            # 2-2. 预测掩码的NLL Loss
            mask_loss = self.criterion(mask_lm_output.transpose(1, 2), data["bert_label"])

            # 2-3. 添加next_loss和mask_loss：3.4预训练过程
            loss = next_loss + mask_loss

            # 3. 仅在训练过程中反向传播和进行优化器优化
            if train:
                self.optim_schedule.zero_grad()
                loss.backward()
                self.optim_schedule.step_and_update_lr()

            # 下一句的预测准确度
            correct = next_sent_output.argmax(dim=-1).eq(data["is_next"]).sum().item()
            avg_loss += loss.item()
            total_correct += correct
            total_element += data["is_next"].nelement()

            post_fix = {
                "epoch": epoch,
                "iter": i,
                "avg_loss": avg_loss / (i + 1),
                "avg_acc": total_correct / total_element * 100,
                "loss": loss.item()
            }

            if i % self.log_freq == 0:
                data_iter.write(str(post_fix))

        print("EP%d_%s, avg_loss=" % (epoch, str_code), avg_loss / len(data_iter), "total_acc=",
              total_correct * 100.0 / total_element)

    def save(self, epoch, file_path="output/bert_trained.model"):
        """
        将当前BERT模型保存在文件路径(file_path)上

        :param epoch: 当前的epoch数
        :param file_path: 模型输出路径，将是 file_path + "ep％d" ％epoch
        :return: final_output_path
        """
        output_path = file_path + ".ep%d" % epoch
        torch.save(self.bert.cpu(), output_path)
        self.bert.to(self.device)
        print("EP:%d Model Saved on:" % epoch, output_path)
        return output_path
